package com.example.browser;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;

import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import android.widget.LinearLayout;

import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class Main4Activity extends Activity {
    private ImageView home_search,clear_his;
    private EditText home_edit;
    private RelativeLayout all_evaluate_root_view;
    private LinearLayout cs,search_view;
    private Button search_bt;
    private boolean if_exist;
    private ListView lv;
    private MyDatabaseHelper dbHelper;
    private ArrayList arrayList=new ArrayList();
    private String get_title,get_url;//暂存从数据库得到的title和url
    private int get_id; //暂存从数据库得到的id
    private String titler, url;//按值查找详细信息
    int id; //按值查找id

    private TextView text_www,text_http,cv,privacy,bookmark;
    ViewGroup.LayoutParams lp;
    SharedPreferences share;

    private static final String FILENAME="YX";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);


        home_edit=(EditText) findViewById(R.id.home_edit);
        home_search=(ImageView) findViewById(R.id.home_search);
        search_bt = (Button)findViewById(R.id.search_bt) ;
        all_evaluate_root_view=(RelativeLayout)findViewById(R.id.all_evaluate_root_view) ;
        search_view=(LinearLayout)findViewById(R.id.search_view) ;
        clear_his=(ImageView)findViewById(R.id.clear_his) ;

        cs = (LinearLayout)findViewById(R.id.cs);
        search_view=(LinearLayout)findViewById(R.id.search_view) ;
        all_evaluate_root_view=(RelativeLayout)findViewById(R.id.all_evaluate_root_view) ;
        text_www=(TextView)findViewById(R.id.text_www);
        text_http=(TextView)findViewById(R.id.text_http);
        cv=(TextView)findViewById(R.id.cv);
        privacy=(TextView)findViewById(R.id.privacy);
        bookmark=(TextView)findViewById(R.id.bookmark);

        lv=(ListView)findViewById(R.id.bookmark_list);

         share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
        if(share.getString("night", "夜间模式关闭").equals("夜间模式开启")){
            search_view.setBackgroundResource(R.drawable.night_search);
            all_evaluate_root_view.setBackgroundColor(Color.rgb(105,105,105));
        }
        //点击函数：
        queryinfo();
        buttomBB();

        initViews();

    }

private void buttomBB(){
    //Android进入页面开始就自动弹出软键盘
    //刚进去当整个view还没有构建完毕，执行弹出软键盘是没有效果的，所以这里加了个定时器，当进到页面后200毫秒后才开始弹出软键盘

    home_edit.setFocusable(true);
    home_edit.setFocusableInTouchMode(true);
    home_edit.requestFocus();
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
                       public void run() {
                           InputMethodManager inputManager =
                                   (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                           inputManager.showSoftInput(home_edit, 0);
                       }
                   },
            300);
    //原文链接：https://blog.csdn.net/qq_43319748/article/details/106641138,问题：动态改变布局
    SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
        @Override
        public void keyBoardShow(int height) {

            // Toast.makeText(Main4Activity.this, "输入法打开", Toast.LENGTH_SHORT).show();
            //按照屏幕比例设置
            DisplayMetrics displayMetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int displayheight = displayMetrics.heightPixels;//高度
            int displayWidth = displayMetrics.widthPixels;//宽度
            lp= cs.getLayoutParams();
            lp.width=displayWidth ;
            lp.height= (int) (displayheight*0.06);
            cs.setLayoutParams(lp);
            cs.setVisibility(View.VISIBLE);

            SharedPreferences.Editor edit=share.edit();
            if(share.getString("night", "夜间模式关闭").equals("夜间模式开启")){
                cs.setBackgroundColor(Color.rgb(108,108,108));
                text_http.setBackgroundColor(Color.rgb(211,211,211));
                text_www.setBackgroundColor(Color.rgb(211,211,211));
                cv.setBackgroundColor(Color.rgb(211,211,211));
                bookmark.setBackgroundColor(Color.rgb(211,211,211));
                bookmark.setTextColor(Color.parseColor("#46A3FF"));
                cv.setTextColor(Color.parseColor("#46A3FF"));
                if(share.getString("privacy", "无痕模式【关闭】").equals("无痕模式【关闭】")){
                    privacy.setTextColor(Color.parseColor("#46A3FF"));
                    privacy.setBackgroundColor(Color.rgb(211,211,211));//转换网址https://www.sioe.cn/yingyong/yanse-rgb-16/
                    queryinfo();
                }else if(share.getString("privacy", "无痕模式【关闭】").equals("无痕模式【开启】")){
                    privacy.setTextColor(Color.parseColor("#ffffff"));
                    privacy.setBackgroundColor(Color.rgb(40,148,255));//2894FF 40,148,255
                }
            }else {
                cs.setBackgroundColor(Color.rgb(240,240,240));
                bookmark.setBackgroundColor(Color.rgb(210,233,255));
                bookmark.setTextColor(Color.parseColor("#46A3FF"));
                text_http.setBackgroundColor(Color.rgb(255,255,255));
                cv.setBackgroundColor(Color.rgb(210,233,255));
                text_www.setBackgroundColor(Color.rgb(255,255,255));
                cv.setTextColor(Color.parseColor("#46A3FF"));
                if(share.getString("privacy", "无痕模式【关闭】").equals("无痕模式【关闭】")){
                    privacy.setTextColor(Color.parseColor("#46A3FF"));
                    privacy.setBackgroundColor(Color.rgb(210,233,255));//转换网址https://www.sioe.cn/yingyong/yanse-rgb-16/
                    queryinfo();
                }else if(share.getString("privacy", "无痕模式【关闭】").equals("无痕模式【开启】")){
                    privacy.setTextColor(Color.parseColor("#ffffff"));
                    privacy.setBackgroundColor(Color.rgb(40,148,255));//2894FF 40,148,255
                }
            }




            bookmark.setText("书签");


            cv.setText("剪贴板");

            text_http.setText("https://");

            text_www.setText("www.");



            privacy.setText("无痕模式");
            text_www.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    home_edit.setText(home_edit.getText().toString()+"www.");
                    String content=home_edit.getText().toString();
                    home_edit.setSelection(content.length());//光标定位到后面


                }
            });
            text_http.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    home_edit.setText(home_edit.getText().toString()+"https://");
                    String content=home_edit.getText().toString();
                    home_edit.setSelection(content.length());

                }
            });
            privacy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    //  SharedPreferences存储、查看   https://blog.csdn.net/u013441613/article/details/80361817
                    if(share.getString("privacy", "无痕模式【关闭】").equals("无痕模式【关闭】")){
                        //取数据的两个参数，第一个是key值，第二是默认值表示当传入的键找不到对应的值时会已默认值返回。
                        //因此没有必要存就可以直接判断,因此这里的if语句执行成功再存
                        edit.putString("privacy", "无痕模式【开启】");//存

                        edit.commit();
                        privacy.setTextColor(Color.parseColor("#ffffff"));
                        privacy.setBackgroundColor(Color.rgb(40,148,255));//2894FF 40,148,255
                        Toast.makeText(Main4Activity.this, "无痕模式开启", Toast.LENGTH_SHORT).show();

//                            lp = lv.getLayoutParams();
//                            lp.height=0;
//                            lv.setLayoutParams(lp);
                        arrayList.clear();
                        queryinfo();

                    }else if(share.getString("privacy", "无痕模式【关闭】").equals("无痕模式【开启】")){
                        edit.putString("privacy", "无痕模式【关闭】");
                        edit.commit();
                        privacy.setTextColor(Color.parseColor("#46A3FF"));
                        privacy.setBackgroundColor(Color.rgb(210,233,255));


                        queryinfo();


                        Toast.makeText(Main4Activity.this, "无痕模式关闭", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            bookmark.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent();
                    intent.setClass(Main4Activity.this,bookmark.class);
                    startActivity(intent);
                }
            });
            cv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(Main4Activity.this,dialog_cv.class);//没有任何参数（意图），只是用来传递数据
                    startActivity(intent);
                }
            });



        }
        @Override
        public void keyBoardHide(int height) {

            //Toast.makeText(Main4Activity.this, "输入法关闭", Toast.LENGTH_SHORT).show();

            cs.setVisibility(View.GONE);

        }
    });

}


    private void initViews() {

//默认百度搜索
        SharedPreferences share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
        String searchhistory = share.getString("searchurl", "https://www.baidu.com/s?wd=");
        if(searchhistory.equals("https://www.baidu.com/s?wd=")){
            Main4Activity.this.home_search.setImageResource(R.drawable.baidu);
        }else if(searchhistory.equals("https://www.sogou.com/web?query=")){
            Main4Activity.this.home_search.setImageResource(R.drawable.sougou);
        }else if(searchhistory.equals("http://www.google.com.tw/search?q=")){
            Main4Activity.this.home_search.setImageResource(R.drawable.chrome);
        }else if(searchhistory.equals("https://cn.bing.com/search?q=")){
            Main4Activity.this.home_search.setImageResource(R.drawable.bing);
        }else if(searchhistory.equals("https://quark.sm.cn/s?q=")){
            Main4Activity.this.home_search.setImageResource(R.drawable.quak);
        }else {
            home_search.setImageResource(R.drawable.iconyx);
        }
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (if_exist) {
                    dealWithIntent();
                    Intent intent = new Intent(Main4Activity.this, webview.class);//没有任何参数（意图），只是用来传递数据
                    intent.putExtra("searchText",query_by_id3(position));
                    startActivity(intent);
                    finish();
                }


            }
        });
        //长按选择删除
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (if_exist)
                    delete_dialog(position);
                return true;
            }
        });


        //监听编辑框
        home_edit.addTextChangedListener(new EditChangedListener());
//搜索按钮
        search_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 先隐藏键盘
//                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
//                        .hideSoftInputFromWindow(Main4Activity.this.getCurrentFocus()
//                                .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断

                search();
            }
        });

////接收来自主页传来的搜索引擎，更改对应的搜索图标并将传递到webview的搜索引擎更改
//        if(searchpic.equals("https://www.baidu.com/s?wd=")){
//            Main4Activity.this.home_search.setImageResource(R.drawable.baidu);
//            surl = "https://www.baidu.com/s?wd=";
//        }else if (searchpic.equals("https://www.sogou.com/web?query=")){
//            Main4Activity.this.home_search.setImageResource(R.drawable.sougou);
//            surl = "https://www.sogou.com/web?query=";
//        }else if (searchpic.equals("https://www.google.com/search?q=")){
//            Main4Activity.this.home_search.setImageResource(R.drawable.chrome);
//            surl = "https://www.google.com/search?q=";
//        }else  if(searchpic.equals("http://cn.bing.com/search?q=")){
//            Main4Activity.this.home_search.setImageResource(R.drawable.bing);
//            surl = "http://cn.bing.com/search?q=";
//        }

        //键盘回车搜索
        home_edit.setOnKeyListener(new View.OnKeyListener() {
            @Override

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
// 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(Main4Activity.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                    search();
                }
                return false;
            }
        });

        home_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Main4Activity.this,MainActivity2.class);
                startActivityForResult(intent,2);


            }
        });

    }

    //搜索方法
    private void search() {
        String searchContext = home_edit.getText().toString().trim();
        if (TextUtils.isEmpty(searchContext)) {
            Toast.makeText(Main4Activity.this,"输入框为空",Toast.LENGTH_SHORT).show();
        } else {
            history(home_edit.getText().toString());
//传递数据
            dealWithIntent();


            Intent it = new Intent(Main4Activity.this, webview.class);
            //传递搜索框内容
            it.putExtra("searchText",home_edit.getText().toString().trim());
//获取搜素引擎返回的数据再传递
            startActivityForResult(it,6);
            finish();
        }
    }

    //数据库逆序查询函数：
    public void queryinfo(){
        SharedPreferences share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
        SharedPreferences.Editor edit=share.edit();
        final ArrayList<HashMap<String, Object>> listItem = new ArrayList <HashMap<String,Object>>();/*在数组中存放数据*/
        //第二个参数是数据库名
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //Cursor cursor = db.rawQuery("select * from bookmarkDB", null);
        //查询语句也可以这样写
        Cursor cursor = db.query("search_hisDB", null, null, null, null, null, "id desc");
        if (cursor != null && cursor.getCount() > 0) {
            if_exist=true;
            while(cursor.moveToNext()) {
                get_id=cursor.getInt(0);//得到int型的自增变量
                get_title = cursor.getString(1);

                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("title", get_title);
                map.put("search_pic",String.valueOf(R.drawable.search));
                arrayList.add(get_id);
                listItem.add(map);
                //new String  数据来源， new int 数据到哪去
                SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.search_hiszujian,
                        new String[] {"title","search_pic"},
                        new int[] {R.id.search_histxt,R.id.search_icon});
                lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
                edit.putString("clear_search","显示图标");
                edit.commit();
                clear_his.setImageResource(R.drawable.trash);
                clear_his.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        delete_all_dialog();
                    }
                });
            }
        }
        else {
            if_exist=false;
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("title", "");

            listItem.add(map);
            //new String  数据来源， new int 数据到哪去
            SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.search_hiszujian,
                    new String[] {"title"},
                    new int[] {R.id.search_histxt});
            lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器

            edit.putString("clear_search","不显示图标");
            edit.commit();
            clear_his.setImageResource(0);
        }

        cursor.close();
        db.close();
    }
    //数据库添加数据(搜索历史表)
    public void history(String title){
        //第二个参数是数据库名
        MyDatabaseHelper  dbHelper = new MyDatabaseHelper(Main4Activity.this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("history", title);

        //insert（）方法中第一个参数是表名，第二个参数是表示给表中未指定数据的自动赋值为NULL。第三个参数是一个ContentValues对象
        db.insert("search_hisDB",null,values);

    }
    //bookmarkDB删除函数：
    public void delete(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("search_hisDB","id=?",new String[] {String.valueOf(arrayList.get(position))});
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        //删除后清空数组，重新放入数据，刷新UI
        arrayList.clear();
        queryinfo();


    }
    public String query_by_id3(int position) {
        dbHelper = new MyDatabaseHelper(this, "dmbrowser.db", null, 1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from search_hisDB", null);
        while (cursor.moveToNext()) {

            titler = cursor.getString(1);
            id = cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return titler;
    }
    //全部删除
    public void delete_all(){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from search_hisDB", null);
        while (cursor.moveToNext()) {
            id=cursor.getInt(0);
            db.delete("search_hisDB","id=?",new String[] {String.valueOf(id)});
        }
        cursor.close();
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        //删除后清空数组，重新放入数据，刷新UI
        arrayList.clear();
        //刷新UI
        queryinfo();


    }

    //bookmarkDB全部删除对话框
    public void delete_all_dialog(){
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setIcon(R.drawable.iconyx)
                .setTitle("确定全部删除吗？")//设置对话框的标题
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delete_all();
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();

    }
    //bookmarkDB全部删除对话框
    public void delete_dialog(int position){
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("确定删除吗？")//设置对话框的标题
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delete(position);
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();

    }
    //获取返回搜索url
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        SharedPreferences share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
        SharedPreferences.Editor edit=share.edit();
        String searchhistory = share.getString("searchurl", "https://www.baidu.com/s?wd=");

        if (requestCode==2){
            if(resultCode==2){
                if(searchhistory.equals("https://www.baidu.com/s?wd=")){
                    Main4Activity.this.home_search.setImageResource(R.drawable.baidu);

                }else if(searchhistory.equals("https://www.sogou.com/web?query=")){
                    Main4Activity.this.home_search.setImageResource(R.drawable.sougou);

                }else if(searchhistory.equals("http://www.google.com.tw/search?q=")){
                    Main4Activity.this.home_search.setImageResource(R.drawable.chrome);

                }else if(searchhistory.equals("http://cn.bing.com/search?q=")){
                    Main4Activity.this.home_search.setImageResource(R.drawable.bing);

                }else if(searchhistory.equals("https://quark.sm.cn/s?q=")){
                    Main4Activity.this.home_search.setImageResource(R.drawable.quak);

                }
//                surl=data.getStringExtra("burl");
//
//                //设置搜索图标
//                if(surl.equals("https://www.baidu.com/s?wd=")){
//                    Main4Activity.this.home_search.setImageResource(R.drawable.baidu);
//                    edit.putString("yh","百度");
//                    edit.commit();
//                }else if (surl.equals("https://www.sogou.com/web?query=")){
//                    Main4Activity.this.home_search.setImageResource(R.drawable.sougou);
//
//                    edit.putString("yh","搜狗");
//                    edit.commit();
//                }else if (surl.equals("https://www.google.com/search?q=")){
//                    Main4Activity.this.home_search.setImageResource(R.drawable.chrome);
//
//                    edit.putString("yh","谷歌");
//                    edit.commit();
//                }else  if(surl.equals("http://cn.bing.com/search?q=")){
//                    Main4Activity.this.home_search.setImageResource(R.drawable.bing);
//                    Intent intent = new Intent();
//                    intent.putExtra("burl","http://cn.bing.com/search?q=");
//                    setResult(3,intent);
//                }
            }
        }

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //finish();点击窗口外部区域 弹窗消失
        //点击空白处关闭键盘
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        if(imm.isActive()&&getCurrentFocus()!=null){
            if (getCurrentFocus().getWindowToken()!=null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }



        return true;
    }

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        finish();//点击窗口外部区域 弹窗消失
//        return true;
//    }

    //监听编辑框--https://www.jb51.net/article/135392.htm
    //https://blog.csdn.net/ycwol/article/details/46594275
    class EditChangedListener implements TextWatcher {
        public void afterTextChanged(Editable arg0) {

// 文字改变后出发事件
            String content = home_edit.getText().toString();
            //若输入框内容不为空按钮可点击，字体为蓝色
            if (!content.isEmpty()) {
                //.setEnabled .setClickable---https://blog.csdn.net/qq_22637473/article/details/54863252
                search_bt.setClickable(true);
                search_bt.setEnabled(true);
                search_bt.setBackgroundResource(R.drawable.cansearch);
            } else {
                search_bt.setClickable(true);
                search_bt.setEnabled(true);
                search_bt.setBackgroundResource(R.drawable.searchbtclick);
            }

        }
        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
// TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub

        }
    };

    /**
     * 判断某一个类是否存在任务栈里面
     * @return
     */
    private boolean isExsitMianActivity(Class<?> cls){
        Intent intent = new Intent(this, cls);
        ComponentName cmpName = intent.resolveActivity(getPackageManager());
        boolean flag = false;
        if (cmpName != null) { // 说明系统中存在这个activity
            ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.baseActivity.equals(cmpName)) { // 说明它已经启动了
                    flag = true;
                    break;  //跳出循环，优化效率
                }
            }
        }
        return flag;
    }
//关闭另外一个activity
    /**
     * 进行逻辑处理
     */
    public void dealWithIntent(){
        if(isExsitMianActivity(webview.class)){//存在这个类
            webview.instance.finish();
        }else{//不存在这个类
            //进行操作
        }
    }


    //退出程序提示
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        SharedPreferences share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
//默认百度搜索
        String searchhistory = share.getString("searchurl", "https://www.baidu.com/s?wd=");
        if(searchhistory.equals("https://www.baidu.com/s?wd=")){
            Main4Activity.this.home_search.setImageResource(R.drawable.baidu);

        }else if(searchhistory.equals("https://www.sogou.com/web?query=")){
            Main4Activity.this.home_search.setImageResource(R.drawable.sougou);

        }else if(searchhistory.equals("http://www.google.com.tw/search?q=")){
            Main4Activity.this.home_search.setImageResource(R.drawable.chrome);

        }else if(searchhistory.equals("http://cn.bing.com/search?q=")){
            Main4Activity.this.home_search.setImageResource(R.drawable.bing);

        }else if(searchhistory.equals("https://quark.sm.cn/s?q=")){
            Main4Activity.this.home_search.setImageResource(R.drawable.quak);

        }
        home_edit.setFocusable(true);
        home_edit.setFocusableInTouchMode(true);
        home_edit.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(home_edit, 0);
                           }
                       },
                300);
    }

}